<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="8"><div class="grid-content bg-purple">
        <div class="developer left">
            <div id="box1">
              <ul>
                <li v-for="(v, index) in districtList" :key="index">
                  <div class="product-content1">
                    <image-preview :src="v.image" alt="Dynamic Image" class="fixed-image-size"/>
                    <div class="info">
                      <h2>{{ v.communityName }}</h2>
                      <h4>{{v.centerPoint}}</h4>
                      <h4>辖区：{{ v.name }}</h4>
                    </div>
                    <div class="additional-info1">
                      <p @click="handlePopulationClick(v.id)">实有人口：{{ v.populationNum }}</p>
                      <p @click="handleEstateClick(v.id)">实有房屋：{{ v.realEstateNum }}</p>
                      <p @click="handleUnitClick(v.id)">实有单位：{{ v.unitNum }}</p>
                      <p @click="handleVehiclesClick(v.id)">实有车辆：{{ v.vehicleNum }}</p>
                      <p @click="handleCacheClick(v.id)">实有力量：{{ v.buildingCount }}</p>
                      <p @click="handleFacilitiesClick(v.id)">实有设备：{{ v.securityFacilitiesNum }}</p>
                    </div>
                  </div>
                </li>
              </ul>
          </div>
        </div>
      </div></el-col>
      <el-col :span="15"><div class="grid-content bg-purple">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入姓名"
              :clearable="true"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="身份证" prop="idCardNumber">
            <el-input
              v-model="queryParams.idCardNumber"
              placeholder="请输入身份证"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="电话号码" prop="iphone">
            <el-input
              v-model="queryParams.iphone"
              placeholder="请输入电话号码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="人员类型" prop="populationTypeId">
            <el-select v-model="queryParams.populationTypeId" :clearable="true" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="身份标签" prop="labelId">
            <el-select v-model="queryParams.labelId" :clearable="true" placeholder="请选择">
              <el-option
                v-for="item in tags"
                :key="item.id"
                :label="item.labelName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <template>
              <el-radio v-model="queryParams.gender" :label="1">男</el-radio>
              <el-radio v-model="queryParams.gender" :label="0">女</el-radio>
            </template>
          </el-form-item>
          <el-form-item label="民族" prop="nation">
            <el-input
              v-model="queryParams.nation"
              placeholder="请输入民族"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="户籍地址" prop="residenceAddress">
            <el-input
              v-model="queryParams.residenceAddress"
              placeholder="请输入户籍地址"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="迁移状态" prop="stats">
            <el-select v-model="queryParams.stats" :clearable="true" placeholder="请选择迁移状态">
              <el-option label="未迁出" value="0"></el-option>
              <el-option label="已迁出" value="1"></el-option>
            </el-select>
          </el-form-item>
<!--          <el-form-item label="是否关联视频身份信息" prop="type_id">-->
<!--            <template>-->
<!--              <el-radio v-model="queryParams.ifVideoIdentity" label="1">是</el-radio>-->
<!--              <el-radio v-model="queryParams.ifVideoIdentity" label="2">否</el-radio>-->
<!--            </template>-->
<!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['population:population:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="handleUpdate"
              v-hasPermi="['population:population:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete"
              v-hasPermi="['population:population:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <label class="el-button el-button--mini el-button--plain" style="cursor: pointer;">
              <input type="file" style="display: none;" @change="handleImport">
              <i class="el-icon-plus"></i> 导入
            </label>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['community:population:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!--小区实有人口-->
        <div id="box">
          <ul class="population-list">
            <li v-for="(v, index) in populationList" :key="index" class="product-item">
              <div class="product-content2">
                <input type="checkbox" v-model="selectedItems" :value="v" class="checkbox-item" @change="handleSelectionChange(v)" />
                <div class="top-right-button">
                  <el-button class="button" @click="showTaskWindow(v)">一键布控</el-button>
                </div>
                <div class="image-container" @click="redirectToPopulationPage(v)">
                  <image-preview :src="v.picture" alt="Dynamic Image" class="fixed-image-size3"/>
                  <h4 class="migration-status" v-if="v.stats === 1">
                    已迁出
                  </h4>
                  <div class="label" :style="{ backgroundColor: v.randomColor }">
                    <h4>{{v.populationTypeName}}</h4>
                  </div>
                </div>
                <div class="info">
                  <h4>姓名：{{v.name}} 最近出现：{{v.lastTime}}</h4>
                  <h4>性别：{{ v.gender == '1' ? '男' : '女' }}</h4>
                  <h4>民族：{{ v.nation }} 电话：{{v.iphone}}</h4>
                  <h4>小区地址：{{ v.communityName }}</h4>
                  <h4>证件号码：{{ v.idCardNumber }}</h4>
                  <h4>户籍地址：{{ v.residenceAddress }}</h4>
                  <el-tag v-if="v.labelNames!==null" type="success">{{ v.labelNames }}</el-tag>
                </div>
              </div>
            </li>
          </ul>
        </div>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div></el-col>
    </el-row>

    <!-- 添加或修改实有人口统计对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="身份证号码" prop="idCardNumber">
          <el-input
            v-model="form.idCardNumber"
            placeholder="请输入身份证号码"
            @blur="onIdCardBlur"
          />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio v-model="form.gender" :label="1">男</el-radio>
          <el-radio v-model="form.gender" :label="0">女</el-radio>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="户籍所在地" prop="residenceAddress">
          <el-input v-model="form.residenceAddress" placeholder="请输入户籍所在地" />
        </el-form-item>
        <el-form-item label="人员类型" prop="type_id">
          <el-select v-model="form.populationTypeId" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="picture">
          <ImageUpload v-model="form.picture" />
        </el-form-item>
        <el-form-item label="居住地址" prop="residenceAddress">
          <el-select v-model="form.districtId" placeholder="所在小区" @change="handleChange(form.districtId)">
            <el-option
              v-for="item in districtLists"
              :key="item.id"
              :label="item.communityName"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="form.ridgepole" placeholder="楼栋号" @change="handleChangeridgepole">
            <el-option
              v-for="item in ridgepoleList"
              :key="item.id"
              :label="item.ridgepole"
              :value="item.ridgepole">
            </el-option>
          </el-select>
          <el-select v-model="form.element" placeholder="单元号" @change="handleChangeelement">
            <el-option
              v-for="item in elementList"
              :key="item.id"
              :label="item.element"
              :value="item.element">
            </el-option>
          </el-select>
          <el-select v-model="form.households" placeholder="门牌号" @change="handlehouseholdsChange">
            <el-option
              v-for="item in householdsList"
              :key="item.id"
              :label="item.households"
              :value="item.households">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="登记时间" prop="registrationDate">
          <el-date-picker clearable
            v-model="form.registrationDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择登记时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="电话" prop="iphone">
          <el-input v-model="form.iphone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="民族" prop="nation">
          <el-input v-model="form.nation" placeholder="请输入民族" />
        </el-form-item>
          <el-form-item label="人员标签" prop="labelIds">
            <el-select
              v-model="form.labelIds"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择人员标签">
              <el-option
                v-for="item in tags"
                :key="item.id"
                :label="item.labelName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelTr">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改抓拍任务对话框 -->
    <el-dialog title="一键布控" :visible.sync="openTask" width="500px" append-to-body :close-on-click-modal="false" :rules="rules">
      <el-form ref="form" :model="deployForm" :rules="deployRules" label-width="80px">
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
                          v-model="deployForm.startTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
                          v-model="deployForm.endTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务等级" prop="level">
          <el-input type="number" v-model="deployForm.level" placeholder="请输入任务等级" />
        </el-form-item>
        <el-form-item label="相似度设置" prop="similarity">
          <el-slider v-model="deployForm.similarity"></el-slider>
        </el-form-item>
        <el-form-item label="任务描述" prop="desc">
          <el-input v-model="deployForm.taskDesc" placeholder="请输入任务描述" />
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-radio-group v-model="deployForm.taskType">
            <el-radio
              v-for="dict in dict.type.deploy_task_type"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleAddPopulationTask">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>
<style scoped>
#box {
  height: 400px;
  overflow-y: auto;
}
.top-right-button {
  position: absolute;
  right: 0;
  top: 0;
}
.button {
  width: 50px;
  height: 25px;
  font-size: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  box-sizing: border-box;
}
.migration-status {
  position: absolute; /* 绝对定位 */
  bottom: 19px; /* 调整到底部 */
  right: 2px; /* 紧贴右侧 */
  transform: rotate(35deg); /* 旋转35度实现倾斜效果，方向调整为右上角到左下角 */
  background-color: #6E6E6E; /* 背景颜色设为较深的灰色 */
  color: #9E9E9E; /* 字体颜色设为较浅的灰色 */
  padding: 8px 15px; /* 内边距 */
  border-radius: 5px; /* 边框圆角 */
  display: inline-block; /* 使背景只覆盖文本区域 */
  z-index: 10; /* 确保在其他元素上方 */
  margin: 0; /* 移除默认margin */
  font-weight: bold; /* 使文本更突出 */
  box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3); /* 添加阴影，提升立体感 */
}
  .product-content1 {
  text-align: center; /* 图片和信息居中对齐 */
  margin-bottom: 20px; /* 底部间距 */
}

  .product-content1 .fixed-image-size {
  display: block; /* 确保图片是块级元素 */
  margin: 0 auto 10px auto; /* 图片居中并留下一定的底部间距 */
  max-width: 100%; /* 图片最大宽度为容器宽度 */
  height: 500px; /* 高度自适应，保持比例 */
  width: 500px; /* 固定宽度，可以根据需要调整 */
}

  #box {
  display: flex;
  justify-content: center; /* 居中显示 */
}

  .population-list {
  display: flex;
  flex-wrap: wrap;
  padding: 0;
  margin: 0;
  list-style: none;
}
  .product-item {
  width: calc(33.33% - 20px); /* 计算每个项目的宽度，减去外边距 */
  margin: 10px; /* 外边距 */
}

  .product-content2 {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 10px;
    border: 1px solid #ccc;
    width: 100%; /* 确保每个项目占据父容器的宽度 */
  }

  .product-content2 .fixed-image-size2 {
  display: block; /* 确保图片是块级元素 */
  margin: 0 auto 10px auto; /* 图片居中并留下一定的底部间距 */
  max-width: 100%; /* 图片最大宽度为容器宽度 */
  height: 200px; /* 高度自适应，保持比例 */
  width: 200px; /* 固定宽度，可以根据需要调整 */
}

  .info {
  flex: 1; /* 让信息部分占据剩余空间 */
}
.info h4, .info el-tag, .info input {
  display: block; /* 每个项单独显示一行 */
  margin-bottom: 5px; /* 可选：设置项之间的间距 */
  word-wrap: break-word; /* 长单词或 URL 换行 */
}

  .info h4,
  .info p, .info el-tag{
  margin: 0;
}

  .additional-info1 {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 三列布局 */
  grid-gap: 10px; /* 设置网格之间的间距 */
}

  .additional-info1 p {
  margin: 0;
}
  .product-item {
    list-style: none;
    margin-bottom: 10px;
  }
  .label {
    position: absolute;
    top: 10px;
    left: 10px;
    /**background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
    /**background-color: rgba(250, 218, 221, 0.5); /* 浅粉色背景，半透明 */
    background-color: rgba(0, 0, 255, 0.5);
    color: white;
    padding: 5px;
    border-radius: 3px;
    font-size: 12px;
  }

  .checkbox-item {
    margin-right: 5px;
  }
  .product-item {
    list-style: none;
    margin-bottom: 10px;
  }

  .image-container{
    position: relative;
    display: inline-block;
  }
.image-container .fixed-image-size3{
  width: 150px;
  height: 200px;
}
  .label {
    position: absolute;
    top: 0;
    left: 0;
    color: white;
    padding: 5px;
    /* 其他样式根据需要调整 */
    border-radius: 3px;
    font-size: 12px;
    /* 背景颜色将通过 :style 绑定动态生成 */
  }
</style>

<script>
import {
  addPopulation,
  delPopulation,
  getElementList,
  getHouseholdsList,
  getLabelList,
  getPopulation,
  getPopulationType,
  handleimport,
  listPopulation,
  listRidgepole,
  updatePopulation
} from "@/api/community/population";
import {getDistrictSelect, listDistrict} from "@/api/community/district";
import ImageUpload from '@/components/ImageUpload'
import {addPopulationFace} from "../../../api/deploy/face";


export default {
  name: "Population",
  dicts: ['sys_user_sex', 'deploy_task_type'],
  components: { ImageUpload },
  data() {
    return {
      openTask: false,
      deployForm: {},
      labelLists: [],
      ridgepoleList:[],
      elementList: [],
      householdsList: [],
      tags:{},
      options:{},
      currentView: '', // 控制显示哪个盒子
      populationNum: 0,
      buildingCount: 0,
      selectedItems:[],
      dialogVisible: false,
      selectedFile:null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      //single: true,
      // 非多个禁用
      // multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实有人口统计表格数据
      populationList: [],
      districtList:[],
      districtLists:[],
      name:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        id:null,
        pageNum: 1,
        pageSize: 10,
        name: null,
        gender: null,
        picture: null,
        age: null,
        idCardNumber: null,
        residenceAddress: null,
        registrationDate: null,
        iphone: null,
        nation: null,
        districtId: localStorage.getItem('districtId'),
        typeId:null,
        labelId: null,
        stats:null,
        ids:[],
      },
      // 表单参数
      form: {
        districtId:localStorage.getItem('districtId'),
        labelIds:[],
        labelId:null,
        labelNames:null,
        ridgepole:null,
        element:null,
        households:null,
      },
      queryParam:{},
      deployRules:{
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' },
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' },
        ],
        level: [
          { required: true, message: '请输入任务等级', trigger: 'blur' },
        ],
        similarity: [
          { required: true, message: '请设置相似度', trigger: 'change' },
        ],
        taskDesc: [
          { required: true, message: '请输入任务描述', trigger: 'blur' },
        ],
        taskType: [
          { required: true, message: '请选择任务类型', trigger: 'change' },
        ],
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        idCardNumber: [
          { required: true, message: "身份证号码不能为空", trigger: "blur" }
        ],
        districtId: [
          { required: true, message: '请选择小区', trigger: 'change' }
        ],
      },
      taskPersonId: null
    };
  },
  created() {
    var id = this.$route.params.id
    if (id != null && id != undefined && id !== '') {
      localStorage.setItem('districtId', id);
    }
    this.getList();
    this.getDistrictList();
    this.getDistrictLists();
    this.getPopulationType();
    this.initRandomColors();
    this.labelList();
    this.getDistrictList();
  },
  methods: {
    // 当身份证号码输入框失去焦点时触发
    onIdCardBlur() {
      const idCardNumber = this.form.idCardNumber.trim();
      if (this.validateIdCard(idCardNumber)) {
        const { gender, age } = this.parseIdCard(idCardNumber);
        this.form.gender = gender;
        this.form.age = age;
      }
    },
    // 验证身份证号码是否有效（简单示例）
    validateIdCard(idCardNumber) {
      const regex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[Xx0-9]$/;
      return regex.test(idCardNumber);
    },
    // 解析身份证号码以获取性别和年龄
    parseIdCard(idCardNumber) {
      const gender = idCardNumber.charAt(16) % 2 === 0 ? 0 : 1; // 性别：0为女性，1为男性
      const birthYear = parseInt(idCardNumber.substr(6, 4), 10);
      const age = this.calculateAge(birthYear); // 计算年龄
      return { gender, age };
    },
    // 根据出生年份计算年龄
    calculateAge(birthYear) {
      const currentYear = new Date().getFullYear();
      return currentYear - birthYear;
    },
    handleAddPopulationTask() {
      // 表单校验
      this.$refs["form"].validate(valid => {
        if (valid) {
          addPopulationFace(this.deployForm, this.taskPersonId).then(response => {
            if (response.code === 200){
              this.$message.success("布控成功");
              this.openTask = false;
              this.reset()
            }
          })
        }else {
          this.$message.error("请填写必填项");
          return false;
        }
      })

    },
    // 一键布控窗口
    showTaskWindow(info) {
      this.deployForm.taskImages = info.picture
      this.taskPersonId = info.id
      this.openTask = true;
    },
    // 查询人员标签
    labelList() {
      getLabelList().then(response => {
        this.tags = response.data;
      });
    },
    // 生成随机颜色
    getRandomColor() {
      const letters = '0123456789ABCDEF';
      let color = '#';
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    },
    // 初始化每个条目的随机颜色
    initRandomColors() {
      this.populationList.forEach(item => {
        item.randomColor = this.getRandomColor();
      });
    },
    // 查询小区 实有人口
    handlePopulationClick(id) {
      this.$router.push({
        path: '/community/population/' + id,
        name: 'Population',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有房屋
    handleEstateClick(id) {
      this.$router.push({
        path: '/community/estate/' + id,
        name: 'Estate',
        params: {
          id: id
        }
      })
    },

    // 查询小区 实有单位
    handleUnitClick(id) {
      this.$router.push({
        path: '/community/unit/' + id,
        name: 'Unit',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有车辆
    handleVehiclesClick(id) {
      this.$router.push({
        path: '/community/vehicles/' + id,
        name: 'Vehicles',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有设备
    handleFacilitiesClick(id) {
      this.$router.push({
        path: '/community/facilities/' + id,
        name: 'Facilities',
        params: {
          id: id
        }
      })
    },
    // 跳转至一人一档页面
    redirectToPopulationPage(item) {
      this.$router.push({
        path: '/person/document/' + item,
        name: 'Document',
        params: {
          item: item
        }
      })
    },
    // 查询小区 实有力量
    handleCacheClick() {
      alert('待开发');
    },
    handleOpen(){
      this.dialogVisible=true;
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    /** 查询小区下拉框 */
    getDistrictLists(){
      getDistrictSelect(this.queryParam).then(response => {
        this.districtLists = response.data;
      });
    },

    handleChange(id){
      listRidgepole(id).then(res=>{
        this.ridgepoleList=res.data
      })
    },

    handleChangeridgepole(ids){
      const selectedItem = this.ridgepoleList.find(item => item.ridgepole === ids);
      if (selectedItem) {
        this.form.labelId = selectedItem.id;
      }
      const did = this.form.districtId;
      const id = this.form.ridgepole;
      if(id!=null){
        getElementList(id,did).then(res=>{
          this.elementList=res.data
        })
      }else {
        this.elementList=[]
      }
    },
    handleChangeelement(id){
      const selectedItem = this.elementList.find(item => item.element === id);
      if (selectedItem) {
        this.form.labelId = selectedItem.id;
      }
      const element = this.form.element;
      const ridgepole = this.form.ridgepole;
      const did = this.form.districtId;
      if(element!=null){
        getHouseholdsList(element,ridgepole,did).then(res=>{
          this.householdsList=res.data
        })
      }else {
        this.householdsList=[]
      }
    },

    handlehouseholdsChange(id){
      const selectedItem = this.householdsList.find(item => item.households === id);
      if (selectedItem) {
        this.form.labelId = selectedItem.id;
      }
    },


    // 查询人员类型下拉框
    getPopulationType(){
      getPopulationType().then(response => {
        this.options = response.data;
      });
    },
    /** 查询实有人口统计列表 */
    getList() {
      this.loading = true;
      var item = localStorage.getItem('districtId')
      this.queryParams.districtId = item
      listPopulation(this.queryParams).then(response => {
        this.populationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    getDistrictList() {
      this.loading = true;
      var item = localStorage.getItem('districtId')
      this.queryParams.id = item
      listDistrict(this.queryParams).then(response => {
        this.districtList = response.rows;
        const promises = this.districtList.map(district => {
          const strings = district.centerPoint.split(",");
          const location = [strings[0], strings[1]];
          localStorage.setItem('communityName',district.communityName)

          return this.getAddressByLocation(location);
        });

        Promise.all(promises).then(addresses => {
          this.districtList.forEach((district, index) => {
            district.centerPoint = addresses[index];
          });
          this.loading = false;
        }).catch(error => {
          console.error('加载或解析地址失败', error);
          this.loading = false;
        });

        this.loading = false;
      });
    },


    getAddressByLocation(location) {
      return new Promise((resolve, reject) => {
        const geocoder = new AMap.Geocoder({
          radius: 1000, // 返回结果周边的范围，单位：米
          extensions: 'all', // 是否返回扩展信息
        });

        geocoder.getAddress(location, (status, result) => {
          let formatted = '解析失败';
          if (status === 'complete' && result.info === 'OK') {
            if (result && result.regeocode) {
              formatted = result.regeocode.formattedAddress;
            } else {
              formatted = '未找到地址信息';
            }
          } else {
            formatted = "地址解析失败";
          }
          resolve(formatted);
        });
      });
    },
    // 一键布控取消按钮
    handleCancel() {
      this.openTask = false;
      this.reset();
    },
    // 取消按钮
    cancel() {
      this.openTask = false;
      this.reset();
    },
    cancelTr(){
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        gender: null,
        picture: null,
        age: null,
        idCardNumber: null,
        residenceAddress: null,
        registrationDate: null,
        iphone: null,
        nation: null,
        populationId: null,
        labelId:null,
        districtId: localStorage.getItem('communityName'),
        ridgepole:null,
        element:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(item) {
      const id = item.id;
      const name = item.name;
      if (this.selectedItems.includes(item)) {
        if (!this.ids.includes(item)) {
          this.ids.push(id);
          this.name.push(name);
        }
      } else {
        const index = this.ids.indexOf(id);
        if (index !== -1) {
          this.ids.splice(index, 1);
        }
        const index1 = this.name.indexOf(name);
        if (index1 !== -1) {
          this.name.splice(index1, 1);
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加实有人口统计";
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset(); // 重置数据（假设这是清空表单等操作的方法）
      if (this.ids.length === 1) {
        const id = this.ids[0];
        const name = this.name[0];
        this.$message.info("开始修改操作，用户：" + name);
        getPopulation(id).then(response => {
          this.form = response.data;
          if(this.form.labelNames){
            this.form.labelIds=this.form.labelNames.split(',').map(id => parseInt(id));
          }
          this.open = true;
          this.title = "修改实有人口统计";
        });
      } else if (this.ids.length > 1) {
        this.$message.warning("每次只能修改一个实有人口统计，请选择单个项目进行修改。");
      } else {
        this.$message.warning("请选择一个实有人口统计项目进行修改。");
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            console.log('this.form',this.form);
            updatePopulation(this.form).then(response => {
              this.ids=[]
              this.name=[]
              this.selectedItems=[]
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPopulation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getDistrictList()
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete() {
      // 先判断是否选中
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择需要删除的实有人口统计");
        return;
      }
      const ids = this.ids;
      const name = this.name;
      this.$modal.confirm('是否确认删除实有人口统计名称为"' + name + '"的数据项？').then(function() {
        return delPopulation(ids);
      }).then(() => {
        this.ids=[]
        this.name=[]
        this.selectedItems=[]
        this.getList();
        this.getDistrictList()
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.labelIds = this.ids;
      this.download('community/community/export', {
        ...this.queryParams
      }, `population_${new Date().getTime()}.xlsx`)
      this.ids=[]
      this.name=[]
      this.selectedItems=[]
    },

    /** 导入按钮操作 */
    handleImport(event) {
      const file = event.target.files[0]; // 获取上传的文件
        handleimport(file).then(res => {
          if (res && res.code === 200) {
            window.location.reload();
            this.$modal.msgSuccess("导入成功");
          }else {
            this.$modal.msgError("导入失败");
          }
        });
    }
  }
};
</script>
